package org.linlinjava.litemall.wx.task;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.system.SystemConfig;
import org.linlinjava.litemall.core.task.Task;
import org.linlinjava.litemall.core.util.BeanUtil;
import org.linlinjava.litemall.db.domain.LitemallActivityGroupon;
import org.linlinjava.litemall.db.domain.LitemallOrder;
import org.linlinjava.litemall.db.service.LitemallActivityService;
import org.linlinjava.litemall.db.service.LitemallOrderService;
import org.linlinjava.litemall.db.util.OrderUtil;

import java.time.LocalDateTime;

public class ActivityOrderUnpaidTask extends Task {

    private final Log logger = LogFactory.getLog(ActivityOrderUnpaidTask.class);
    private int orderId = -1;

    public ActivityOrderUnpaidTask(Integer orderId, long delayInMilliseconds) {
        super("ActivityOrderUnpaidTask-" + orderId, delayInMilliseconds);
        this.orderId = orderId;
    }

    public ActivityOrderUnpaidTask(Integer orderId) {
        super("ActivityOrderUnpaidTask-" + orderId, SystemConfig.getOrderUnpaid() * 60 * 1000);
        this.orderId = orderId;
    }

    @Override
    public void run() {
        logger.info("系统开始处理延时任务---订单超时未付款---" + this.orderId);

        LitemallOrderService orderService = BeanUtil.getBean(LitemallOrderService.class);
        LitemallActivityService activityService = BeanUtil.getBean(LitemallActivityService.class);

        LitemallOrder order = orderService.findById(this.orderId);
        if (order == null) {
            return;
        }
        if (!OrderUtil.isCreateStatus(order)) {
            return;
        }

        // 设置订单已取消状态
        order.setOrderStatus(OrderUtil.STATUS_AUTO_CANCEL);
        order.setEndTime(LocalDateTime.now());
        if (orderService.updateWithOptimisticLocker(order) == 0) {
            throw new RuntimeException("更新数据已失效");
        }

        LitemallActivityGroupon groupon = activityService.findByOrderId(order.getId());
        if (groupon != null) {
            groupon.setState(LitemallActivityGroupon.StateEnum.FAIL.getCode());
            groupon.setPayState(LitemallActivityGroupon.PayStateEnum.FAIL.getCode());
            activityService.updateActivityGrouponById(groupon);
        }

        logger.info("系统结束处理延时任务---订单超时未付款---" + this.orderId);
    }
}
